<template>
  <div class="app-container">
    <div class="container">
      <el-dialog
        :title="state ? '添加用户' : '修改用户'"
        :visible.sync="dialogVisible"
        :before-close="handleClose"
        width="30%"
      >
        <el-form
          ref="ruleForm"
          :model="userForm"
          :rules="rules"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-row>
            <el-col>
              <el-form-item label="用户名" prop="username">
                <el-input v-model="userForm.username" />
              </el-form-item>
            </el-col>
            <el-col>
              <el-form-item label="密码" prop="password">
                <el-input v-model="userForm.password" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col>
              <el-form-item label="姓名" prop="name">
                <el-input v-model="userForm.name" />
              </el-form-item>
            </el-col>
            <el-col>
              <el-form-item label="手机号" prop="phone">
                <el-input v-model="userForm.phone" />
              </el-form-item>
            </el-col>
          </el-row>
          <!-- <el-row>
            <el-col>
              <el-form-item label="状态" prop="status">
                <el-input v-model="userForm.status" />
              </el-form-item>
            </el-col>
          </el-row> -->
          <el-form-item>
            <el-button type="primary" @click="submitForm('ruleForm')">{{
              state ? '添加' : '修改'
            }}</el-button>
            <!-- <el-button @click="resetForm('ruleForm')">重置</el-button> -->
          </el-form-item>
        </el-form>
      </el-dialog>
      <div class="operate-box">
        <div class="input-box">
          <el-input
            v-model="conds.keyword"
            size="small"
            placeholder="请输入内容"
          />
          <el-button
            type="primary"
            size="small"
            plain
            icon="el-icon-search"
            @click="search"
          >搜索</el-button>
        </div>
        <div class="btn-box operate-btn">
          <el-button
            type="success"
            size="small"
            plain
            icon="el-icon-check"
            @click="addUser"
          >添加</el-button>
          <el-popconfirm title="确定批量永久删除吗？" @confirm="batchDel">
            <el-button
              slot="reference"
              type="danger"
              size="small"
              plain
              icon="el-icon-delete"
            >删除</el-button>
          </el-popconfirm>
        </div>
      </div>
      <el-table
        ref="multipleTable"
        v-loading="listLoading"
        :data="list"
        tooltip-effect="dark"
        style="width: 100%"
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" align="center" />
        <el-table-column align="center" type="index" label="ID" width="45" />
        <el-table-column label="用户名">
          <template slot-scope="scope">
            {{ scope.row.username }}
          </template>
        </el-table-column>
        <el-table-column label="姓名" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column label="手机号" align="center">
          <template slot-scope="scope">
            {{ scope.row.phone }}
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          prop="created_at"
          label="创建时间"
          width="200"
        >
          <template slot-scope="scope">
            <div v-if="scope.row.createTime">
              <i class="el-icon-time" />&nbsp;
              <span>{{ scope.row.createTime | formattedDate }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          prop="created_at"
          label="修改时间"
          width="200"
        >
          <template slot-scope="scope">
            <div v-if="scope.row.updateTime">
              <i class="el-icon-time" />&nbsp;
              <span>{{ scope.row.updateTime | formattedDate }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column class-name="status-col" label="状态" align="center">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.status"
              :active-value="1"
              :inactive-value="0"
              active-color="#13ce66"
              inactive-color="#ff4949"
              @change="change(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template slot-scope="operate">
            <el-button
              type="primary"
              circle
              size="small"
              icon="el-icon-edit"
              @click="editUser(operate.row)"
            />
              &nbsp;
            <el-popconfirm
              title="确定永久删除吗？"
              @confirm="deleteUser(operate.row)"
            >
              <el-button
                slot="reference"
                type="danger"
                circle
                size="small"
                icon="el-icon-delete"
              />
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        :current-page="currentPage"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="conds.size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="conds.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
  </div>
</template>

<script>
import { getList } from '@/api/table'
import { updateStatus } from '@/api/user'
export default {
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'gray',
        deleted: 'danger'
      }
      return statusMap[status]
    },
    formattedDate(time) {
      const date = new Date(time)
      const year = date.getFullYear()
      const month = (date.getMonth() + 1).toString().padStart(2, '0')
      const day = date.getDate().toString().padStart(2, '0')
      const hour = date.getHours().toString().padStart(2, '0')
      const minute = date.getMinutes().toString().padStart(2, '0')
      const second = date.getSeconds().toString().padStart(2, '0')
      const formattedDate = `${year}-${month}-${day} ${hour}:${minute}:${second}`
      return formattedDate
    }
  },
  data() {
    return {
      state: true,
      dialogVisible: false,
      list: null,
      listLoading: true,
      currentPage: 1,
      conds: {
        page: 1,
        size: 5,
        total: 0,
        keyword: ''
      },
      userForm: {
        username: null,
        password: null,
        name: null,
        phone: null,
        headUrl: null,
        deptId: null,
        postId: null,
        description: null,
        status: null
      },
      multipleSelection: [],
      rules: {
        username: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
        phone: [{ required: true, message: '请输入手机号', trigger: 'blur' }],
        age: [{ required: true, message: '请输入年龄', trigger: 'blur' }],
        sex: [{ required: true, message: '请选择活动区域', trigger: 'change' }]
      }
    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.state) {
            // add(this.userForm)
            this.dialogVisible = false
            this.getUserList()
            this.$message({
              message: '添加成功',
              type: 'success'
            })
          } else {
            // update(this.userForm)
            this.dialogVisible = false
            this.getUserList()
            this.$message({
              message: '修改成功',
              type: 'success'
            })
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    handleClose(done) {
      // this.state = !this.state
      this.dialogVisible = false
      this.userForm = {}
    },
    search() {
      this.fetchData()
    },
    batchDel() {},
    deleteUser(row) {},
    addUser() {
      this.state = true
      this.dialogVisible = true
      this.userForm = {
        status: 1
      }
    },
    editUser(row) {
      this.state = false
      const old = JSON.parse(JSON.stringify(row))
      this.userForm = old
      this.dialogVisible = true
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
      this.conds.size = val
      this.fetchData()
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`)
      this.conds.page = val
      this.fetchData()
    },
    toggleSelection(rows) {
      if (rows) {
        rows.forEach((row) => {
          this.$refs.multipleTable.toggleRowSelection(row)
        })
      } else {
        this.$refs.multipleTable.clearSelection()
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val.map((item) => item.id)
      console.log(this.multipleSelection)
    },
    fetchData() {
      this.listLoading = true
      getList(this.conds).then((response) => {
        this.list = response.data.records
        this.conds.total = response.data.total
        this.conds.page = response.data.current
        this.conds.size = response.data.size
        this.listLoading = false
      })
    },
    async change(row) {
      const data = await updateStatus(row)
      if (data.code === 200) {
        this.fetchData()
        this.$message({
          message: '修改成功',
          type: 'success'
        })
      } else {
        this.$message({
          message: '修改失败',
          type: 'error'
        })
      }
    },
    add(data) {
      this.state = true
      this.dialogVisible = true
      this.userForm = {
        username: '',
        phone: '',
        status: 1
      }
    }
  }
}
</script>

<style lang="scss">
.el-pagination {
  height: 30px;
  margin-top: 20px;
  text-align: center;
}

.operate-box {
  display: flex;
  margin-bottom: 20px;
}

.input-box {
  display: flex;
  width: 250px;
  .el-input {
    margin-right: 10px;
  }
}

.btn-box.operate-btn .el-button:not(:last-child){
  margin-right: 10px;
}

.btn-box {
  margin-left: 10px;
}
</style>
